package com.huike.business.service.impl;


import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.bean.BeanUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商机跟进记录Service业务层处理
 * 
 * @author wgl
 * @date 2021-04-28
 */
@Service
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {

    @Autowired
    private TbBusinessTrackRecordMapper tbBusinessTrackRecordMapper;

    @Autowired
    private TbBusinessMapper businessMapper;


    @Override
    public void add(BusinessTrackVo businessTrackVo) {
        // 1. 新增商机跟进记录
        TbBusinessTrackRecord businessTrackRecord = new TbBusinessTrackRecord();
        String username = SecurityUtils.getUsername();
        BeanUtils.copyProperties(businessTrackVo,businessTrackRecord);
        businessTrackRecord.setCreateBy(username);
        businessTrackRecord.setCreateTime(new Date());
        tbBusinessTrackRecordMapper.add(businessTrackRecord);

        // 2. 更新商机
        TbBusiness business = new TbBusiness();
        BeanUtils.copyProperties(businessTrackVo,business);
        business.setId(businessTrackVo.getBusinessId());
        business.setRemark(businessTrackVo.getRemark());
        businessMapper.updateTbBusiness(business);
    }

    @Override
    public List<TbBusinessTrackRecord> queryList(Long id) {
        List<TbBusinessTrackRecord> businessTrackRecordList = tbBusinessTrackRecordMapper.querList(id);
        List<TbBusinessTrackRecord> result = businessTrackRecordList.stream().map(businessRecord -> {
            String keyItems = businessRecord.getKeyItems();
            if (!Strings.isEmpty(keyItems)){

                String[] strings = keyItems.split(",");
                List<String> dictItems = new ArrayList<>();
                for (String string : strings) {
                    String label = tbBusinessTrackRecordMapper.queryDictLabel(string);
                    dictItems.add(label);
                }
                businessRecord.setKeys(dictItems);



            }
            return businessRecord;
        }).collect(Collectors.toList());


        return result;
    }
}
